using System.Net;
using Toolbox.Common;
using Toolbox.DnsService.Events;
using Toolbox.DnsService.Interfaces;
using Toolbox.DnsService.Services;
using DnsTestResult = Toolbox.DnsService.Models.DnsTestResult;
using LocalDnsService = Toolbox.DnsService.Services.LocalDnsService;
using DnsConfigManager = Toolbox.DnsService.Services.DnsConfigManager;

namespace Toolbox.Model.DNSService
{
    /// <summary>
    /// DNS服务页面
    /// 提供DNS服务器管理、本地DNS服务和DNS记录管理功能
    /// 作者：huobing
    /// </summary>
    public partial class DNSServicePage : BaseTabPage, IDisposable
    {
        #region BaseTabPage 抽象成员实现

        /// <summary>
        /// 页签名称
        /// </summary>
        public override string TabName => "DNS";

        /// <summary>
        /// 配置文件名称（不含路径和扩展名）
        /// </summary>
        public override string ConfigFileName => "DNSService";

        /// <summary>
        /// 页签序号（用于排序）
        /// </summary>
        public override int TabOrder => 3;

        #region 字段和属性

        /// <summary>
        /// DNS服务器列表
        /// </summary>
        private List<DNSServer>? _dnsServers;

        /// <summary>
        /// 本地DNS服务实例
        /// </summary>
        private IDnsService? _localDnsService;

        /// <summary>
        /// DNS配置管理器实例
        /// </summary>
        private IDnsConfigManager? _dnsConfigManager;

        /// <summary>
        /// 主窗口引用
        /// </summary>
        private MainForm? _mainForm;

        /// <summary>
        /// 页签控件
        /// </summary>
        private TabPage? _tabPage;

        /// <summary>
        /// 主面板
        /// </summary>
        private Panel? _mainPanel;

        /// <summary>
        /// DNS服务器设置组
        /// </summary>
        private GroupBox? _dnsServerGroup;

        /// <summary>
        /// 本地DNS服务组
        /// </summary>
        private GroupBox? _localDnsGroup;

        /// <summary>
        /// 结果显示组
        /// </summary>
        private GroupBox? _resultGroup;

        /// <summary>
        /// DNS服务器下拉框
        /// </summary>
        private ComboBox? _dnsServerComboBox;

        /// <summary>
        /// 测试DNS按钮
        /// </summary>
        private Button? _testDnsButton;

        /// <summary>
        /// 当前DNS信息标签
        /// </summary>
        private Label? _currentDnsLabel;

        /// <summary>
        /// 应用DNS按钮
        /// </summary>
        private Button? _applyDnsButton;

        /// <summary>
        /// 刷新DNS缓存按钮
        /// </summary>
        private Button? _refreshDnsButton;

        /// <summary>
        /// 进度条
        /// </summary>
        private ProgressBar? _progressBar;

        /// <summary>
        /// 端口标签
        /// </summary>
        private Label? _portLabel;

        /// <summary>
        /// 端口输入框
        /// </summary>
        private TextBox? _portTextBox;

        /// <summary>
        /// 上游DNS服务器标签
        /// </summary>
        private Label? _upstreamDnsLabel;

        /// <summary>
        /// 上游DNS服务器输入框
        /// </summary>
        private TextBox? _upstreamDnsTextBox;
        private Button? _saveOrReloadButton;

        /// <summary>
        /// 启动本地DNS按钮
        /// </summary>
        private Button? _startLocalDnsButton;

        /// <summary>
        /// 停止本地DNS按钮
        /// </summary>
        private Button? _stopLocalDnsButton;

        /// <summary>
        /// 测试本地DNS按钮
        /// </summary>
        private Button? _testLocalDnsButton;

        /// <summary>
        /// 测试域名输入框
        /// </summary>
        private TextBox? _testDomainTextBox;

        /// <summary>
        /// 测试域名标签
        /// </summary>
        private Label? _testDomainLabel;

        /// <summary>
        /// DNS记录列表
        /// </summary>
        private ListBox? _dnsRecordsListBox;

        /// <summary>
        /// 添加DNS记录按钮
        /// </summary>
        private Button? _addDnsRecordButton;

        /// <summary>
        /// 编辑DNS记录按钮
        /// </summary>
        private Button? _editDnsRecordButton;

        /// <summary>
        /// 删除DNS记录按钮
        /// </summary>
        private Button? _deleteDnsRecordButton;

        /// <summary>
        /// 日志文本框
        /// </summary>
        private TextBox? _logTextBox;

        /// <summary>
        /// 清除日志按钮
        /// </summary>
        private Button? _clearLogButton;

        /// <summary>
        /// 自动启动复选框
        /// </summary>
        private CheckBox? _autoStartCheckBox;

        /// <summary>
        /// DNS记录缓存
        /// </summary>
        private Dictionary<string, string>? _dnsCache;

        /// <summary>
        /// 资源释放标志
        /// </summary>
        private bool _disposed;

        /// <summary>
        /// 启动本地DNS服务
        /// </summary>
        private void StartLocalDnsService()
        {
            // 从配置文件获取端口和上游DNS服务器
            int port = 153; // 默认端口
            string upstreamDns = "8.8.8.8"; // 默认上游DNS
            bool enableLogging = true; // 默认启用日志

            try
            {
                // 尝试从配置文件加载
                if (_dnsConfigManager != null)
                {
                    DnsService.Models.DnsServiceConfig config = _dnsConfigManager.LoadConfig();
                    port = config.Port;
                    if (config.UpstreamDnsServers.Count > 0)
                    {
                        upstreamDns = config.UpstreamDnsServers[0];
                    }
                    enableLogging = config.EnableLogging;
                }
            }
            catch (Exception ex)
            {
                AddLog($"加载本地DNS服务配置失败，使用默认值: {ex.Message}");
            }

            try
            {
                // 创建本地DNS服务，传入上游DNS服务器地址
                _localDnsService = new LocalDnsService(port, upstreamDns);

                // 配置日志记录
                if (_localDnsService is LocalDnsService localDnsService)
                {
                    localDnsService.EnableLogging(enableLogging);

                    // 如果启用了日志，设置日志记录器
                    if (enableLogging)
                    {
                        try
                        {
                            // 创建日志记录器，使用配置中的日志文件路径
                            string logFilePath = "logs/dns_service.log";
                            if (_dnsConfigManager != null)
                            {
                                DnsService.Models.DnsServiceConfig config = _dnsConfigManager.LoadConfig();
                                if (!string.IsNullOrEmpty(config.LogFilePath))
                                {
                                    logFilePath = config.LogFilePath;
                                }
                            }

                            // 创建文件流作为日志输出
                            TextWriter logWriter = File.CreateText(logFilePath);
                            IDnsLogger logger = new ConsoleDnsLogger(logWriter);
                            localDnsService.SetLogger(logger);
                        }
                        catch (Exception ex)
                        {
                            AddLog($"创建DNS日志记录器失败: {ex.Message}");
                        }
                    }
                }

                // 设置DNS记录
                if (_dnsCache != null)
                {
                    foreach (KeyValuePair<string, string> kvp in _dnsCache)
                    {
                        _ = (_localDnsService?.AddDnsRecord(kvp.Key, kvp.Value));
                    }
                }

                // 启动服务
                if (_localDnsService != null)
                {
                    // 添加事件处理程序，以便输出日志
                    _localDnsService.DnsRequestProcessed += OnDnsRequestProcessed;
                    _localDnsService.StatusChanged += OnDnsServiceStatusChanged;

                    bool success = _localDnsService.Start();
                    if (!success)
                    {
                        AddLog($"启动本地DNS服务失败，端口: {port}，请检查端口是否被占用");
                        return;
                    }
                }

                // 更新UI状态
                if (_portLabel != null)
                {
                    _portLabel.Enabled = false;
                }

                if (_portTextBox != null)
                {
                    _portTextBox.Enabled = false;
                    _portTextBox.Text = port.ToString();
                }

                if (_upstreamDnsLabel != null)
                {
                    _upstreamDnsLabel.Enabled = false;
                }

                if (_upstreamDnsTextBox != null)
                {
                    _upstreamDnsTextBox.Enabled = false;
                    _upstreamDnsTextBox.Text = upstreamDns;
                }

                if (_startLocalDnsButton != null)
                {
                    _startLocalDnsButton.Enabled = false;
                }

                if (_stopLocalDnsButton != null)
                {
                    _stopLocalDnsButton.Enabled = true;
                }

                if (_saveOrReloadButton != null)
                {
                    _saveOrReloadButton.Text = "重载";
                    _saveOrReloadButton.Enabled = true;
                }

                AddLog($"本地DNS服务已启动，端口: {port}，上游DNS: {upstreamDns}，日志记录: {(enableLogging ? "已启用" : "已禁用")}");
            }
            catch (Exception ex)
            {
                AddLog($"启动本地DNS服务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 自动启动本地DNS服务
        /// </summary>
        private void AutoStartLocalDnsService()
        {
            try
            {
                // 检查配置中是否设置了自动启动
                if (_dnsConfigManager != null)
                {
                    DnsService.Models.DnsServiceConfig config = _dnsConfigManager.LoadConfig();
                    if (config.AutoStart)
                    {
                        AddLog("配置中设置了自动启动本地DNS服务，正在启动...");
                        StartLocalDnsService();
                    }
                }
            }
            catch (Exception ex)
            {
                AddLog($"检查自动启动配置失败: {ex.Message}");
            }
        }

        #endregion
        /// 初始化页签页面
        /// </summary>
        /// <param name="tabPage">页签控件</param>
        /// <param name="mainForm">主窗口引用</param>
        public override void InitializePage(TabPage tabPage, MainForm mainForm)
        {
            _tabPage = tabPage;
            _mainForm = mainForm;

            // 初始化字段
            _dnsServers = [];
            _localDnsService = new LocalDnsService();
            _dnsConfigManager = new DnsConfigManager("Conf/DNSService.conf");
            _dnsCache = [];

            // 创建UI控件
            CreateMainPanel();
            InitializeDnsServerGroup();
            InitializeLocalDnsServiceGroup();
            InitializeResultDisplayGroup();

            // 加载配置
            LoadConfiguration();

            // 设置事件处理
            SetupEventHandlers();

            // 初始化控件宽度
            AdjustControlWidths();

            // 自动启动本地DNS服务
            AutoStartLocalDnsService();
        }

        #endregion

        #region 初始化方法

        /// <summary>
        /// 创建主面板
        /// </summary>
        private void CreateMainPanel()
        {
            _mainPanel = new Panel
            {
                Dock = DockStyle.Fill,
                AutoScroll = true,
                Padding = new Padding(10)
            };
            _tabPage!.Size = new Size(530, 600);
            _tabPage.Controls.Add(_mainPanel);
        }

        /// <summary>
        /// 初始化DNS服务器组
        /// </summary>
        private void InitializeDnsServerGroup()
        {
            // 创建DNS服务器设置组
            _dnsServerGroup = CreateDnsServerGroup();
            _mainPanel!.Controls.Add(_dnsServerGroup);
        }

        /// <summary>
        /// 初始化本地DNS服务组
        /// </summary>
        private void InitializeLocalDnsServiceGroup()
        {
            // 创建本地DNS服务组
            _localDnsGroup = CreateLocalDnsServiceGroup();
            _localDnsGroup.Top = _dnsServerGroup!.Bottom + 10;
            _mainPanel!.Controls.Add(_localDnsGroup);
        }

        /// <summary>
        /// 初始化RESULT DISPLAY GROUP
        /// </summary>
        private void InitializeResultDisplayGroup()
        {
            // 创建RESULT DISPLAY GROUP
            _resultGroup = CreateResultDisplayGroup();
            _resultGroup.Top = _localDnsGroup!.Bottom + 10;
            _mainPanel!.Controls.Add(_resultGroup);
        }

        /// <summary>
        /// 设置事件处理
        /// </summary>
        private void SetupEventHandlers()
        {
            // DNS服务器事件
            _testDnsButton!.Click += (s, e) => TestDnsButton_Click(s ?? throw new ArgumentNullException(nameof(s)), e);
            _applyDnsButton!.Click += (s, e) => ApplyDnsButton_Click(s ?? throw new ArgumentNullException(nameof(s)), e);
            _refreshDnsButton!.Click += (s, e) => RefreshDnsButton_Click(s ?? throw new ArgumentNullException(nameof(s)), e);

            // 本地DNS服务事件
            _startLocalDnsButton!.Click += (s, e) => StartLocalDnsButton_Click(s ?? throw new ArgumentNullException(nameof(s)), e);
            _stopLocalDnsButton!.Click += (s, e) => StopLocalDnsButton_Click(s ?? throw new ArgumentNullException(nameof(s)), e);
            _testLocalDnsButton!.Click += (s, e) => TestLocalDnsButton_Click(s ?? throw new ArgumentNullException(nameof(s)), e);
            _saveOrReloadButton!.Click += (s, e) => SaveOrReloadButton_Click(s ?? throw new ArgumentNullException(nameof(s)), e);

            // DNS记录事件
            _addDnsRecordButton!.Click += (s, e) => AddDnsRecordButton_Click(s ?? throw new ArgumentNullException(nameof(s)), e);
            _editDnsRecordButton!.Click += (s, e) => EditDnsRecordButton_Click(s ?? throw new ArgumentNullException(nameof(s)), e);
            _deleteDnsRecordButton!.Click += (s, e) => DeleteDnsRecordButton_Click(s ?? throw new ArgumentNullException(nameof(s)), e);

            // 日志事件
            _clearLogButton!.Click += (s, e) => ClearLogButton_Click(s ?? throw new ArgumentNullException(nameof(s)), e);

            // 窗口大小改变事件
            _mainForm!.Resize += (s, e) => MainForm_Resize(s ?? throw new ArgumentNullException(nameof(s)), e);
        }

        #endregion

        #region UI控件创建方法

        /// <summary>
        /// 创建DNS服务器设置组
        /// </summary>
        /// <returns>DNS服务器设置组</returns>
        private GroupBox CreateDnsServerGroup()
        {
            GroupBox group = new()
            {
                Text = "DNS服务器设置",
                Left = 10,
                Width = _mainPanel!.Width - 20,
                Height = 142  // 自动计算高度：最后一个控件的位置+高度+边距
            };

            // DNS服务器标签
            Label dnsLabel = new()
            {
                Text = "DNS服务器:",
                Left = 10,
                Top = 30,
                Width = 100
            };
            group.Controls.Add(dnsLabel);

            // DNS服务器下拉框
            _dnsServerComboBox = new ComboBox
            {
                Left = 120,
                Top = 28,
                Width = 200,
                DropDownStyle = ComboBoxStyle.DropDownList
            };
            group.Controls.Add(_dnsServerComboBox);

            // 测试DNS按钮
            _testDnsButton = new Button
            {
                Text = "测试",
                Left = 330,
                Top = 26,
                Width = 80
            };
            group.Controls.Add(_testDnsButton);

            // 当前DNS信息标签
            _currentDnsLabel = new Label
            {
                Text = "当前DNS: 未设置",
                Left = 10,
                Top = 60,
                Width = 400,
                AutoSize = false
            };
            group.Controls.Add(_currentDnsLabel);

            // 应用DNS按钮
            _applyDnsButton = new Button
            {
                Text = "应用DNS",
                Left = 10,
                Top = 90,
                Width = 100
            };
            group.Controls.Add(_applyDnsButton);

            // 刷新DNS缓存按钮
            _refreshDnsButton = new Button
            {
                Text = "刷新DNS缓存",
                Left = 120,
                Top = 90,
                Width = 120
            };
            group.Controls.Add(_refreshDnsButton);

            // 进度条
            _progressBar = new ProgressBar
            {
                Left = 10,
                Top = 130,
                Width = 400,
                Height = 2,
                Visible = false
            };
            group.Controls.Add(_progressBar);

            return group;
        }

        /// <summary>
        /// 创建本地DNS服务组
        /// </summary>
        /// <returns>本地DNS服务组</returns>
        private GroupBox CreateLocalDnsServiceGroup()
        {
            GroupBox group = new()
            {
                Text = "本地DNS服务",
                Left = 10,
                Width = _mainPanel?.Width - 20 ?? 0,
                Height = 120  // 自动计算高度：最后一个控件的位置+高度+边距
            };

            // 端口标签
            _portLabel = new Label
            {
                Text = "端口:",
                Left = 10,
                Top = 30,
                Width = 50
            };
            group.Controls.Add(_portLabel);

            // 端口输入框
            _portTextBox = new TextBox
            {
                Text = "153",
                Left = 70,
                Top = 28,
                Width = 80
            };
            group.Controls.Add(_portTextBox);

            // 上游DNS服务器标签
            _upstreamDnsLabel = new Label
            {
                Text = "上游DNS:",
                Left = 10,
                Top = 60,
                Width = 80
            };
            group.Controls.Add(_upstreamDnsLabel);

            // 上游DNS服务器输入框
            _upstreamDnsTextBox = new TextBox
            {
                Text = "8.8.8.8",
                Left = 100,
                Top = 58,
                Width = 120
            };
            group.Controls.Add(_upstreamDnsTextBox);

            // 保存/重载按钮
            _saveOrReloadButton = new Button
            {
                Text = "保存",
                Left = 230,
                Top = 56,
                Width = 60
            };
            group.Controls.Add(_saveOrReloadButton);

            // 启动本地DNS按钮
            _startLocalDnsButton = new Button
            {
                Text = "启动",
                Left = 160,
                Top = 28,
                Width = 80
            };
            group.Controls.Add(_startLocalDnsButton);

            // 停止本地DNS按钮
            _stopLocalDnsButton = new Button
            {
                Text = "停止",
                Left = 250,
                Top = 28,
                Width = 80,
                Enabled = false
            };
            group.Controls.Add(_stopLocalDnsButton);

            // 自动启动复选框
            _autoStartCheckBox = new CheckBox
            {
                Text = "自动启动本地DNS服务",
                Left = 10,
                Top = 90,
                Width = 140,
                Checked = false
            };
            group.Controls.Add(_autoStartCheckBox);

            // 测试域名标签
            _testDomainLabel = new Label
            {
                Text = "测试域名:",
                Left = 160,
                Top = 90,
                Width = 70
            };
            group.Controls.Add(_testDomainLabel);

            // 测试域名输入框
            _testDomainTextBox = new TextBox
            {
                Text = "www.baidu.com",
                Left = 230,
                Top = 90,
                Width = 120
            };
            group.Controls.Add(_testDomainTextBox);

            // 测试DNS按钮
            _testLocalDnsButton = new Button
            {
                Text = "测试DNS",
                Left = 360,
                Top = 90,
                Width = 100
            };
            group.Controls.Add(_testLocalDnsButton);

            return group;
        }

        /// <summary>
        /// 创建RESULT DISPLAY GROUP
        /// </summary>
        /// <returns>RESULT DISPLAY GROUP</returns>
        private GroupBox CreateResultDisplayGroup()
        {
            GroupBox group = new()
            {
                Text = "DNS记录管理",
                Left = 10,
                Width = _mainPanel?.Width - 20 ?? 0,
                Height = 300  // 自动计算高度：最后一个控件的位置+高度+边距
            };

            // DNS记录列表
            _dnsRecordsListBox = new ListBox
            {
                Left = 10,
                Top = 30,
                Width = 400,
                Height = 100
            };
            group.Controls.Add(_dnsRecordsListBox);

            // 添加DNS记录按钮
            _addDnsRecordButton = new Button
            {
                Text = "添加",
                Left = 10,
                Top = 140,
                Width = 80
            };
            group.Controls.Add(_addDnsRecordButton);

            // 编辑DNS记录按钮
            _editDnsRecordButton = new Button
            {
                Text = "编辑",
                Left = 100,
                Top = 140,
                Width = 80
            };
            group.Controls.Add(_editDnsRecordButton);

            // 删除DNS记录按钮
            _deleteDnsRecordButton = new Button
            {
                Text = "删除",
                Left = 190,
                Top = 140,
                Width = 80
            };
            group.Controls.Add(_deleteDnsRecordButton);

            // 清除日志按钮
            _clearLogButton = new Button
            {
                Text = "清除日志",
                Left = 410,
                Top = 140,
                Width = 100
            };
            group.Controls.Add(_clearLogButton);

            // 日志文本框
            _logTextBox = new TextBox
            {
                Left = 10,
                Top = 180,
                Width = 490,
                Height = 100,
                Multiline = true,
                ReadOnly = true,
                ScrollBars = ScrollBars.Vertical
            };
            group.Controls.Add(_logTextBox);

            return group;
        }

        #endregion

        #region 配置管理

        /// <summary>
        /// 加载配置
        /// </summary>
        private void LoadConfiguration()
        {
            try
            {
                // 加载DNS服务器列表
                LoadDnsServers();

                // 加载DNS记录
                LoadDnsRecords();

                // 加载本地DNS服务配置
                LoadLocalDnsServiceConfig();

                // 加载DNS缓存
                LoadDnsCacheFromConfig();

                // 更新UI
                UpdateDnsServerComboBox();
                UpdateDnsRecordsListBox();
                UpdateCurrentDnsInfo();
            }
            catch (Exception ex)
            {
                _ = MessageBox.Show($"加载配置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        private void SaveConfiguration()
        {
            try
            {
                // 保存DNS记录
                SaveDnsRecords();

                // 保存本地DNS服务配置
                SaveLocalDnsServiceConfig();

                // 保存DNS缓存
                SaveDnsCacheToConfig();
            }
            catch (Exception ex)
            {
                _ = MessageBox.Show($"保存配置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载本地DNS服务配置
        /// </summary>
        private void LoadLocalDnsServiceConfig()
        {
            try
            {
                if (_dnsConfigManager != null)
                {
                    DnsService.Models.DnsServiceConfig config = _dnsConfigManager.LoadConfig();
                    _portTextBox!.Text = config.Port.ToString();
                    _upstreamDnsTextBox!.Text = string.Join(",", config.UpstreamDnsServers);
                    _autoStartCheckBox!.Checked = config.AutoStart;
                }
            }
            catch (Exception ex)
            {
                AddLog($"加载本地DNS服务配置失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 保存本地DNS服务配置
        /// </summary>
        private void SaveLocalDnsServiceConfig()
        {
            try
            {
                if (_dnsConfigManager != null)
                {
                    DnsService.Models.DnsServiceConfig config = _dnsConfigManager.LoadConfig();

                    // 解析端口
                    if (int.TryParse(_portTextBox!.Text, out int port))
                    {
                        config.Port = port;
                    }

                    // 解析上游DNS服务器
                    string[] upstreamDnsServers = _upstreamDnsTextBox!.Text.Split(',', StringSplitOptions.RemoveEmptyEntries);
                    config.UpstreamDnsServers.Clear();
                    foreach (string server in upstreamDnsServers)
                    {
                        config.UpstreamDnsServers.Add(server.Trim());
                    }

                    // 保存自动启动设置
                    config.AutoStart = _autoStartCheckBox!.Checked;

                    _dnsConfigManager.SaveConfig(config);
                }
            }
            catch (Exception ex)
            {
                AddLog($"保存本地DNS服务配置失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 加载DNS服务器列表
        /// </summary>
        private void LoadDnsServers()
        {
            if (_dnsServers == null)
            {
                return;
            }

            _dnsServers.Clear();

            // 添加常用DNS服务器
            _dnsServers.Add(new DNSServer("Google DNS", "8.8.8.8", "8.8.4.4"));
            _dnsServers.Add(new DNSServer("Cloudflare DNS", "1.1.1.1", "1.0.0.1"));
            _dnsServers.Add(new DNSServer("阿里DNS", "223.5.5.5", "223.6.6.6"));
            _dnsServers.Add(new DNSServer("腾讯DNS", "119.29.29.29", "182.254.116.116"));
            _dnsServers.Add(new DNSServer("114 DNS", "114.114.114.114", "114.114.115.115"));
        }

        /// <summary>
        /// 加载DNS记录
        /// </summary>
        private void LoadDnsRecords()
        {
            if (_dnsCache == null)
            {
                return;
            }

            _dnsCache.Clear();

            try
            {
                if (_dnsConfigManager != null)
                {
                    DnsService.Models.DnsServiceConfig config = _dnsConfigManager.LoadConfig();
                    if (config.DnsCache != null)
                    {
                        foreach (KeyValuePair<string, string> kvp in config.DnsCache)
                        {
                            _dnsCache[kvp.Key] = kvp.Value;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                AddLog($"加载DNS记录失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 保存DNS记录
        /// </summary>
        private void SaveDnsRecords()
        {
            try
            {
                if (_dnsConfigManager != null && _dnsCache != null)
                {
                    DnsService.Models.DnsServiceConfig config = _dnsConfigManager.LoadConfig();
                    config.DnsCache = _dnsCache;
                    _dnsConfigManager.SaveConfig(config);
                }
            }
            catch (Exception ex)
            {
                AddLog($"保存DNS记录失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 从配置加载DNS缓存
        /// </summary>
        private void LoadDnsCacheFromConfig()
        {
            try
            {
                if (_dnsConfigManager != null)
                {
                    DnsService.Models.DnsServiceConfig config = _dnsConfigManager.LoadConfig();
                    if (config.DnsCache != null)
                    {
                        _dnsCache = new Dictionary<string, string>(config.DnsCache);
                    }
                }
            }
            catch (Exception ex)
            {
                AddLog($"加载DNS缓存失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 保存DNS缓存到配置
        /// </summary>
        private void SaveDnsCacheToConfig()
        {
            try
            {
                if (_dnsConfigManager != null && _dnsCache != null)
                {
                    DnsService.Models.DnsServiceConfig config = _dnsConfigManager.LoadConfig();
                    config.DnsCache = _dnsCache;
                    _dnsConfigManager.SaveConfig(config);
                }
            }
            catch (Exception ex)
            {
                AddLog($"保存DNS缓存失败: {ex.Message}");
            }
        }

        #endregion

        #region UI更新方法

        /// <summary>
        /// 更新DNS服务器下拉框
        /// </summary>
        private void UpdateDnsServerComboBox()
        {
            if (_dnsServerComboBox == null || _dnsServers == null)
            {
                return;
            }

            _dnsServerComboBox.Items.Clear();

            foreach (DNSServer server in _dnsServers)
            {
                _ = _dnsServerComboBox.Items.Add(server.Name);
            }

            if (_dnsServers.Count > 0)
            {
                _dnsServerComboBox.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// 更新DNS记录列表
        /// </summary>
        private void UpdateDnsRecordsListBox()
        {
            if (_dnsRecordsListBox == null || _dnsCache == null)
            {
                return;
            }

            _dnsRecordsListBox!.Items.Clear();

            foreach (KeyValuePair<string, string> kvp in _dnsCache!)
            {
                _ = _dnsRecordsListBox.Items.Add($"{kvp.Key} -> {kvp.Value}");
            }
        }

        /// <summary>
        /// 更新当前DNS信息
        /// </summary>
        private void UpdateCurrentDnsInfo()
        {
            if (_currentDnsLabel == null)
            {
                return;
            }

            try
            {
                List<string> currentDns = DnsUtilities.GetCurrentDnsServers();
                _currentDnsLabel.Text = $"当前DNS: {string.Join(", ", currentDns)}";
            }
            catch (Exception ex)
            {
                _currentDnsLabel.Text = $"当前DNS: 获取失败 - {ex.Message}";
            }
        }

        /// <summary>
        /// 添加日志信息
        /// </summary>
        /// <param name="message">日志消息</param>
        private void AddLog(string message)
        {
            if (_logTextBox!.InvokeRequired)
            {
                _ = _logTextBox.Invoke(new Action<string>(AddLog), message);
            }
            else
            {
                _logTextBox.AppendText($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}{Environment.NewLine}");
            }
        }

        /// <summary>
        /// 处理DNS请求事件
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void OnDnsRequestProcessed(object? sender, DnsRequestEventArgs e)
        {
            string cacheStatus = e.IsCached ? "缓存" : "上游查询";
            AddLog($"DNS请求: {e.Domain} -> {e.ResolvedIp} ({cacheStatus}, 来源: {e.RemoteEndPoint?.Address?.ToString() ?? "未知"})");
        }

        /// <summary>
        /// 处理DNS服务状态变化事件
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void OnDnsServiceStatusChanged(object? sender, DnsServiceStatusEventArgs e)
        {
            AddLog($"DNS服务状态: {e.Message}");
        }

        #endregion

        #region 事件处理方法

        /// <summary>
        /// 测试DNS按钮点击事件
        /// </summary>
        private void TestDnsButton_Click(object sender, EventArgs e)
        {
            if (_dnsServerComboBox!.SelectedIndex < 0 || _dnsServerComboBox.SelectedIndex >= _dnsServers!.Count)
            {
                _ = MessageBox.Show("请选择DNS服务器", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            DNSServer? selectedServer = null;
            if (_dnsServerComboBox.SelectedIndex >= 0 && _dnsServerComboBox.SelectedIndex < _dnsServers.Count)
            {
                selectedServer = _dnsServers[_dnsServerComboBox.SelectedIndex];
            }

            // 测试域名解析
            TestDomainResolution(selectedServer?.PrimaryDns ?? string.Empty, "www.baidu.com");
        }

        /// <summary>
        /// 应用DNS按钮点击事件
        /// </summary>
        private void ApplyDnsButton_Click(object sender, EventArgs e)
        {
            if (_dnsServerComboBox!.SelectedIndex < 0 || _dnsServerComboBox.SelectedIndex >= _dnsServers!.Count)
            {
                _ = MessageBox.Show("请选择DNS服务器", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            DNSServer selectedServer = _dnsServers[_dnsServerComboBox.SelectedIndex];

            try
            {
                // 显示进度条
                if (_progressBar != null)
                {
                    _progressBar.Visible = true;
                    _progressBar.Style = ProgressBarStyle.Marquee;
                }

                // 应用DNS设置
                List<string> dnsServers = [];
                if (!string.IsNullOrEmpty(selectedServer.PrimaryDns))
                {
                    dnsServers.Add(selectedServer.PrimaryDns);
                }
                if (!string.IsNullOrEmpty(selectedServer.SecondaryDns))
                {
                    dnsServers.Add(selectedServer.SecondaryDns);
                }
                bool success = DnsUtilities.SetDnsServers(dnsServers);

                // 隐藏进度条
                if (_progressBar != null)
                {
                    _progressBar.Visible = false;
                }

                if (success)
                {
                    _ = MessageBox.Show("DNS设置应用成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    UpdateCurrentDnsInfo();
                    AddLog($"已应用DNS设置: {selectedServer.Name} ({selectedServer.PrimaryDns}, {selectedServer.SecondaryDns})");
                }
                else
                {
                    _ = MessageBox.Show("DNS设置应用失败，请以管理员身份运行程序", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                if (_progressBar != null)
                {
                    _progressBar.Visible = false;
                }

                _ = MessageBox.Show($"DNS设置应用失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新DNS缓存按钮点击事件
        /// </summary>
        private void RefreshDnsButton_Click(object sender, EventArgs e)
        {
            try
            {
                // 显示进度条
                if (_progressBar != null)
                {
                    _progressBar.Visible = true;
                    _progressBar.Style = ProgressBarStyle.Marquee;
                }

                // 刷新DNS缓存
                bool success = DnsUtilities.FlushDnsCache();

                // 隐藏进度条
                if (_progressBar != null)
                {
                    _progressBar.Visible = false;
                }

                if (success)
                {
                    _ = MessageBox.Show("DNS缓存刷新成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    AddLog("DNS缓存已刷新");
                }
                else
                {
                    _ = MessageBox.Show("DNS缓存刷新失败，请以管理员身份运行程序", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                if (_progressBar != null)
                {
                    _progressBar.Visible = false;
                }

                _ = MessageBox.Show($"DNS缓存刷新失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 启动本地DNS按钮点击事件
        /// </summary>
        private void StartLocalDnsButton_Click(object sender, EventArgs e)
        {
            if (_portTextBox == null || !int.TryParse(_portTextBox.Text, out int port) || port < 1 || port > 65535)
            {
                _ = MessageBox.Show("请输入有效的端口号(1-65535)", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (_upstreamDnsTextBox == null || string.IsNullOrWhiteSpace(_upstreamDnsTextBox.Text))
            {
                _ = MessageBox.Show("请输入上游DNS服务器地址", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                // 获取上游DNS服务器地址
                string upstreamDns = _upstreamDnsTextBox.Text.Trim();

                // 创建本地DNS服务，传入上游DNS服务器地址
                _localDnsService = new LocalDnsService(port, upstreamDns);

                // 设置DNS记录
                if (_dnsCache != null)
                {
                    foreach (KeyValuePair<string, string> kvp in _dnsCache)
                    {
                        _ = (_localDnsService?.AddDnsRecord(kvp.Key, kvp.Value));
                    }
                }

                // 启动服务
                if (_localDnsService != null)
                {
                    // 添加事件处理程序，以便输出日志
                    _localDnsService.DnsRequestProcessed += OnDnsRequestProcessed;
                    _localDnsService.StatusChanged += OnDnsServiceStatusChanged;

                    bool success = _localDnsService.Start();
                    if (!success)
                    {
                        _ = MessageBox.Show("启动本地DNS服务失败，请检查端口是否被占用", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                // 更新UI状态
                if (_portLabel != null)
                {
                    _portLabel.Enabled = false;
                }

                if (_portTextBox != null)
                {
                    _portTextBox.Enabled = false;
                }

                if (_upstreamDnsLabel != null)
                {
                    _upstreamDnsLabel.Enabled = false;
                }

                if (_upstreamDnsTextBox != null)
                {
                    _upstreamDnsTextBox.Enabled = false;
                }

                if (_startLocalDnsButton != null)
                {
                    _startLocalDnsButton.Enabled = false;
                }

                if (_stopLocalDnsButton != null)
                {
                    _stopLocalDnsButton.Enabled = true;
                }

                if (_saveOrReloadButton != null)
                {
                    _saveOrReloadButton.Text = "重载";
                    _saveOrReloadButton.Enabled = true;
                }

                AddLog($"本地DNS服务已启动，端口: {port}，上游DNS: {upstreamDns}");
            }
            catch (Exception ex)
            {
                _ = MessageBox.Show($"启动本地DNS服务失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 测试本地DNS按钮点击事件
        /// </summary>
        private void TestLocalDnsButton_Click(object sender, EventArgs e)
        {
            if (_localDnsService == null || !_localDnsService.IsRunning)
            {
                _ = MessageBox.Show("请先启动本地DNS服务", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 获取输入框中的域名
            string domain = _testDomainTextBox?.Text?.Trim() ?? string.Empty;
            if (string.IsNullOrWhiteSpace(domain))
            {
                _ = MessageBox.Show("请输入要测试的域名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 测试本地DNS解析
            TestLocalDnsResolution(domain);
        }

        /// <summary>
        /// 测试本地DNS解析
        /// </summary>
        private void TestLocalDnsResolution(string domain)
        {
            if (_localDnsService == null || !_localDnsService.IsRunning)
            {
                _ = MessageBox.Show("本地DNS服务未运行", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                // 获取本地DNS服务端口
                int port = _localDnsService.Port;
                string dnsServer = $"127.0.0.1:{port}";

                // 调用测试方法
                TestDomainResolution(dnsServer, domain);
            }
            catch (Exception ex)
            {
                _ = MessageBox.Show($"测试本地DNS解析失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 保存/重载按钮点击事件
        /// </summary>
        private void SaveOrReloadButton_Click(object sender, EventArgs e)
        {
            if (_localDnsService == null || !_localDnsService.IsRunning)
            {
                // 服务未启动，执行保存操作
                SaveLocalDnsServiceConfig();
                _ = MessageBox.Show("配置已保存", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                AddLog("本地DNS服务配置已保存");
            }
            else
            {
                // 服务已启动，执行重载操作
                try
                {
                    // 获取当前端口和新的上游DNS
                    int port = _localDnsService.Port;
                    string upstreamDns = _upstreamDnsTextBox?.Text?.Trim() ?? "8.8.8.8";

                    // 停止当前服务
                    _localDnsService.Stop();

                    // 创建新服务实例
                    _localDnsService = new LocalDnsService(port, upstreamDns);

                    // 重新添加DNS记录
                    if (_dnsCache != null)
                    {
                        foreach (KeyValuePair<string, string> kvp in _dnsCache)
                        {
                            _ = (_localDnsService?.AddDnsRecord(kvp.Key, kvp.Value));
                        }
                    }

                    // 启动服务
                    bool success = _localDnsService?.Start() ?? false;
                    if (!success)
                    {
                        _ = MessageBox.Show("重载本地DNS服务失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    // 保存配置
                    SaveLocalDnsServiceConfig();

                    _ = MessageBox.Show("配置已重载并生效", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    AddLog($"本地DNS服务已重载，端口: {port}，上游DNS: {upstreamDns}");
                }
                catch (Exception ex)
                {
                    _ = MessageBox.Show($"重载本地DNS服务失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 停止本地DNS按钮点击事件
        /// </summary>
        private void StopLocalDnsButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (_localDnsService != null)
                {
                    // 移除事件处理程序
                    _localDnsService.DnsRequestProcessed -= OnDnsRequestProcessed;
                    _localDnsService.StatusChanged -= OnDnsServiceStatusChanged;

                    // 停止服务
                    _localDnsService.Stop();
                }

                // 更新UI状态
                if (_portLabel != null)
                {
                    _portLabel.Enabled = true;
                }

                if (_portTextBox != null)
                {
                    _portTextBox.Enabled = true;
                }

                if (_upstreamDnsLabel != null)
                {
                    _upstreamDnsLabel.Enabled = true;
                }

                if (_upstreamDnsTextBox != null)
                {
                    _upstreamDnsTextBox.Enabled = true;
                }

                if (_startLocalDnsButton != null)
                {
                    _startLocalDnsButton.Enabled = true;
                }

                if (_stopLocalDnsButton != null)
                {
                    _stopLocalDnsButton.Enabled = false;
                }

                if (_saveOrReloadButton != null)
                {
                    _saveOrReloadButton.Text = "保存";
                    _saveOrReloadButton.Enabled = true;
                }

                AddLog("本地DNS服务已停止");
            }
            catch (Exception ex)
            {
                _ = MessageBox.Show($"停止本地DNS服务失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 添加DNS记录按钮点击事件
        /// </summary>
        private void AddDnsRecordButton_Click(object sender, EventArgs e)
        {
            ShowAddDnsRecordDialog();
        }

        /// <summary>
        /// 编辑DNS记录按钮点击事件
        /// </summary>
        private void EditDnsRecordButton_Click(object sender, EventArgs e)
        {
            if (_dnsRecordsListBox == null || _dnsRecordsListBox.SelectedIndex < 0)
            {
                _ = MessageBox.Show("请选择要编辑的DNS记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 获取选中的记录
            string selectedText = _dnsRecordsListBox?.SelectedItem?.ToString() ?? string.Empty;
            string[] parts = selectedText.Split([" -> "], StringSplitOptions.None);

            if (parts?.Length == 2)
            {
                ShowEditDnsRecordDialog(parts[0], parts[1]);
            }
        }

        /// <summary>
        /// 删除DNS记录按钮点击事件
        /// </summary>
        private void DeleteDnsRecordButton_Click(object sender, EventArgs e)
        {
            if (_dnsRecordsListBox == null || _dnsRecordsListBox.SelectedIndex < 0)
            {
                _ = MessageBox.Show("请选择要删除的DNS记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 获取选中的记录
            string selectedText = _dnsRecordsListBox?.SelectedItem?.ToString() ?? string.Empty;
            string[] parts = selectedText.Split([" -> "], StringSplitOptions.None);

            if (parts?.Length == 2)
            {
                if (MessageBox.Show($"确定要删除DNS记录 {parts[0]} -> {parts[1]} 吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    // 从缓存中删除
                    if (_dnsCache != null)
                    {
                        _ = _dnsCache.Remove(parts[0]);
                    }

                    // 如果本地DNS服务正在运行，更新记录
                    if (_localDnsService != null && _localDnsService.IsRunning)
                    {
                        _ = _localDnsService.RemoveDnsRecord(parts[0]);
                    }

                    // 更新UI
                    UpdateDnsRecordsListBox();

                    // 保存配置
                    SaveConfiguration();

                    AddLog($"已删除DNS记录: {parts[0]} -> {parts[1]}");
                }
            }
        }

        /// <summary>
        /// 清除日志按钮点击事件
        /// </summary>
        private void ClearLogButton_Click(object sender, EventArgs e)
        {
            _logTextBox?.Clear();
        }

        /// <summary>
        /// 主窗口大小改变事件
        /// </summary>
        private void MainForm_Resize(object sender, EventArgs e)
        {
            AdjustControlWidths();
        }

        /// <summary>
        /// 调整控件宽度
        /// </summary>
        private void AdjustControlWidths()
        {
            // 确保主面板已初始化
            if (_mainPanel == null)
            {
                return;
            }

            // 调整控件宽度
            int width = _mainPanel.Width - 40;

            if (_dnsServerGroup != null)
            {
                _dnsServerGroup.Width = width;
            }

            if (_localDnsGroup != null)
            {
                _localDnsGroup.Width = width;
            }

            if (_resultGroup != null)
            {
                _resultGroup.Width = width;
            }

            // 调整内部控件宽度
            if (_dnsServerComboBox != null)
            {
                _dnsServerComboBox.Width = Math.Min(200, width - 150);
            }

            if (_currentDnsLabel != null)
            {
                _currentDnsLabel.Width = width - 20;
            }

            if (_progressBar != null)
            {
                _progressBar.Width = width - 20;
            }

            if (_dnsRecordsListBox != null)
            {
                _dnsRecordsListBox.Width = width - 20;
            }

            if (_logTextBox != null)
            {
                _logTextBox.Width = width - 20;
            }

            // 调整清除日志按钮位置
            if (_clearLogButton != null)
            {
                _clearLogButton.Left = width - 120;
            }

            // 调整测试DNS按钮位置
            if (_testDnsButton != null)
            {
                _testDnsButton.Left = width - 90;
            }

            // 调整刷新DNS缓存按钮位置
            if (_refreshDnsButton != null)
            {
                _refreshDnsButton.Left = 120;
            }

            // 调整停止DNS按钮位置
            if (_stopLocalDnsButton != null)
            {
                _stopLocalDnsButton.Left = 260;
            }
        }

        #endregion

        #region 对话框方法

        /// <summary>
        /// 显示添加DNS记录对话框
        /// </summary>
        private void ShowAddDnsRecordDialog()
        {
            using Form form = new();
            form.Text = "添加DNS记录";
            form.FormBorderStyle = FormBorderStyle.FixedDialog;
            form.MaximizeBox = false;
            form.MinimizeBox = false;
            form.StartPosition = FormStartPosition.CenterParent;
            form.Size = new Size(400, 200);

            // 域名标签
            Label domainLabel = new()
            {
                Text = "域名:",
                Left = 20,
                Top = 20,
                Width = 80
            };
            form.Controls.Add(domainLabel);

            // 域名输入框
            TextBox domainTextBox = new()
            {
                Left = 110,
                Top = 18,
                Width = 250
            };
            form.Controls.Add(domainTextBox);

            // IP地址标签
            Label ipLabel = new()
            {
                Text = "IP地址:",
                Left = 20,
                Top = 60,
                Width = 80
            };
            form.Controls.Add(ipLabel);

            // IP地址输入框
            TextBox ipTextBox = new()
            {
                Left = 110,
                Top = 58,
                Width = 250
            };
            form.Controls.Add(ipTextBox);

            // 确定按钮
            Button okButton = new()
            {
                Text = "确定",
                Left = 220,
                Top = 120,
                Width = 80,
                DialogResult = DialogResult.OK
            };
            form.Controls.Add(okButton);

            // 取消按钮
            Button cancelButton = new()
            {
                Text = "取消",
                Left = 310,
                Top = 120,
                Width = 80,
                DialogResult = DialogResult.Cancel
            };
            form.Controls.Add(cancelButton);

            // 设置接受和取消按钮
            form.AcceptButton = okButton;
            form.CancelButton = cancelButton;

            // 显示对话框
            if (form.ShowDialog(_mainForm) == DialogResult.OK)
            {
                string domain = domainTextBox.Text?.Trim() ?? string.Empty;
                string ip = ipTextBox.Text?.Trim() ?? string.Empty;

                if (string.IsNullOrEmpty(domain) || string.IsNullOrEmpty(ip))
                {
                    _ = MessageBox.Show("域名和IP地址不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 验证IP地址格式
                if (!IPAddress.TryParse(ip, out _))
                {
                    _ = MessageBox.Show("请输入有效的IP地址", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 添加到缓存
                if (_dnsCache != null)
                {
                    _dnsCache[domain] = ip;
                }

                // 如果本地DNS服务正在运行，更新记录
                if (_localDnsService != null && _localDnsService.IsRunning)
                {
                    _ = _localDnsService.AddDnsRecord(domain, ip);
                }

                // 更新UI
                UpdateDnsRecordsListBox();

                // 保存配置
                SaveConfiguration();

                AddLog($"已添加DNS记录: {domain} -> {ip}");
            }
        }

        /// <summary>
        /// 显示编辑DNS记录对话框
        /// </summary>
        /// <param name="domain">域名</param>
        /// <param name="ip">IP地址</param>
        private void ShowEditDnsRecordDialog(string domain, string ip)
        {
            using Form form = new();
            form.Text = "编辑DNS记录";
            form.FormBorderStyle = FormBorderStyle.FixedDialog;
            form.MaximizeBox = false;
            form.MinimizeBox = false;
            form.StartPosition = FormStartPosition.CenterParent;
            form.Size = new Size(400, 200);

            // 域名标签
            Label domainLabel = new()
            {
                Text = "域名:",
                Left = 20,
                Top = 20,
                Width = 80
            };
            form.Controls.Add(domainLabel);

            // 域名输入框
            TextBox domainTextBox = new()
            {
                Text = domain,
                Left = 110,
                Top = 18,
                Width = 250,
                ReadOnly = true
            };
            form.Controls.Add(domainTextBox);

            // IP地址标签
            Label ipLabel = new()
            {
                Text = "IP地址:",
                Left = 20,
                Top = 60,
                Width = 80
            };
            form.Controls.Add(ipLabel);

            // IP地址输入框
            TextBox ipTextBox = new()
            {
                Text = ip,
                Left = 110,
                Top = 58,
                Width = 250
            };
            form.Controls.Add(ipTextBox);

            // 确定按钮
            Button okButton = new()
            {
                Text = "确定",
                Left = 220,
                Top = 120,
                Width = 80,
                DialogResult = DialogResult.OK
            };
            form.Controls.Add(okButton);

            // 取消按钮
            Button cancelButton = new()
            {
                Text = "取消",
                Left = 310,
                Top = 120,
                Width = 80,
                DialogResult = DialogResult.Cancel
            };
            form.Controls.Add(cancelButton);

            // 设置接受和取消按钮
            form.AcceptButton = okButton;
            form.CancelButton = cancelButton;

            // 显示对话框
            if (form.ShowDialog(_mainForm) == DialogResult.OK)
            {
                string newIp = ipTextBox.Text?.Trim() ?? string.Empty;

                if (string.IsNullOrEmpty(newIp))
                {
                    _ = MessageBox.Show("IP地址不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 验证IP地址格式
                if (!IPAddress.TryParse(newIp, out _))
                {
                    _ = MessageBox.Show("请输入有效的IP地址", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 更新缓存
                if (_dnsCache != null)
                {
                    _dnsCache[domain] = newIp;
                }

                // 如果本地DNS服务正在运行，更新记录
                if (_localDnsService != null && _localDnsService.IsRunning)
                {
                    _ = _localDnsService.AddDnsRecord(domain, newIp);
                }

                // 更新UI
                UpdateDnsRecordsListBox();

                // 保存配置
                SaveConfiguration();

                AddLog($"已更新DNS记录: {domain} -> {newIp}");
            }
        }

        #endregion

        #region DNS测试方法

        /// <summary>
        /// 测试域名解析
        /// </summary>
        /// <param name="dnsServer">DNS服务器</param>
        /// <param name="domain">域名</param>
        private void TestDomainResolution(string dnsServer, string domain)
        {
            // 显示进度条
            if (_progressBar != null)
            {
                _progressBar.Visible = true;
                _progressBar.Style = ProgressBarStyle.Marquee;
            }

            // 在后台线程中执行测试
            _ = Task.Run(() =>
            {
                try
                {
                    // 测试域名解析
                    DnsTestResult result = DnsUtilities.TestDnsResolution(dnsServer, domain);

                    // 在UI线程中更新结果
                    _mainForm?.Invoke(new Action(() =>
                    {
                        if (_progressBar != null)
                        {
                            _progressBar.Visible = false;
                        }

                        if (result.IsSuccess)
                        {
                            _ = MessageBox.Show($"域名解析测试成功:\n域名: {domain}\nDNS服务器: {dnsServer}\n解析结果: {result.ResolvedIp ?? "未知"}\n响应时间: {result.ResponseTimeMs}ms",
                                "测试结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            AddLog($"DNS测试成功: {domain} -> {result.ResolvedIp ?? "未知"} (服务器: {dnsServer}, 响应时间: {result.ResponseTimeMs}ms)");
                        }
                        else
                        {
                            _ = MessageBox.Show($"域名解析测试失败:\n域名: {domain}\nDNS服务器: {dnsServer}\n错误: {result.ErrorMessage ?? "未知错误"}",
                                "测试结果", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            AddLog($"DNS测试失败: {domain} (服务器: {dnsServer}, 错误: {result.ErrorMessage ?? "未知错误"})");
                        }
                    }));
                }
                catch (Exception ex)
                {
                    // 在UI线程中显示错误
                    _mainForm?.Invoke(new Action(() =>
                    {
                        if (_progressBar != null)
                        {
                            _progressBar.Visible = false;
                        }
                        _ = MessageBox.Show($"域名解析测试失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        AddLog($"DNS测试异常: {ex.Message}");
                    }));
                }
            });
        }

        #endregion

        #region BaseTabPage 虚方法重写

        /// <summary>
        /// 处理窗口高度变化的通知
        /// </summary>
        /// <param name="tabPage">页签控件</param>
        /// <param name="mainForm">主窗口引用</param>
        /// <param name="currentHeight">当前窗口高度</param>
        public override void OnWindowHeightChanged(TabPage tabPage, MainForm mainForm, int currentHeight)
        {
            // 根据窗口高度调整UI布局
            int availableHeight = currentHeight - 100; // 减去一些边距

            // 调整各控件高度
            if (_dnsServerGroup != null)
            {
                _dnsServerGroup.Height = Math.Min(200, availableHeight / 3);
            }

            if (_localDnsGroup != null && _dnsServerGroup != null)
            {
                _localDnsGroup.Top = _dnsServerGroup.Bottom + 10;
                _localDnsGroup.Height = Math.Min(150, availableHeight / 3);
            }

            if (_resultGroup != null && _localDnsGroup != null)
            {
                _resultGroup.Top = _localDnsGroup.Bottom + 10;
                _resultGroup.Height = Math.Min(300, availableHeight / 3);
            }
        }

        /// <summary>
        /// 停止运行并释放资源
        /// </summary>
        /// <param name="mainForm">主窗口引用</param>
        public override void StopRunning(MainForm mainForm)
        {
            // 停止本地DNS服务
            try
            {
                _localDnsService?.Stop();
            }
            catch (Exception ex)
            {
                // 记录错误但不抛出异常
                System.Diagnostics.Debug.WriteLine($"停止本地DNS服务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理页签切换事件
        /// </summary>
        /// <param name="mainForm">主窗口引用</param>
        public override void OnTabSelected(MainForm mainForm)
        {
            // 更新当前DNS信息
            UpdateCurrentDnsInfo();

            // 如果本地DNS服务未启动，且配置中设置了自动启动，则自动启动
            if (_localDnsService != null && !_localDnsService.IsRunning)
            {
                try
                {
                    // 检查配置中是否设置了自动启动
                    if (_dnsConfigManager != null)
                    {
                        DnsService.Models.DnsServiceConfig config = _dnsConfigManager.LoadConfig();
                        if (config.AutoStart)
                        {
                            AddLog("配置中设置了自动启动本地DNS服务，正在启动...");
                            StartLocalDnsService();
                        }
                    }
                }
                catch (Exception ex)
                {
                    AddLog($"检查自动启动配置失败: {ex.Message}");
                }
            }
        }

        #endregion

        #region 资源释放

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="disposing">是否正在释放托管资源</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    // 释放托管资源
                    _localDnsService?.Stop();
                    _localDnsService?.Dispose();

                    // 释放UI控件
                    _mainPanel?.Dispose();
                    _dnsServerGroup?.Dispose();
                    _localDnsGroup?.Dispose();
                    _resultGroup?.Dispose();
                    _dnsServerComboBox?.Dispose();
                    _testDnsButton?.Dispose();
                    _currentDnsLabel?.Dispose();
                    _applyDnsButton?.Dispose();
                    _refreshDnsButton?.Dispose();
                    _progressBar?.Dispose();
                    _portLabel?.Dispose();
                    _portTextBox?.Dispose();
                    _startLocalDnsButton?.Dispose();
                    _stopLocalDnsButton?.Dispose();
                    _dnsRecordsListBox?.Dispose();
                    _addDnsRecordButton?.Dispose();
                    _editDnsRecordButton?.Dispose();
                    _deleteDnsRecordButton?.Dispose();
                    _logTextBox?.Dispose();
                    _clearLogButton?.Dispose();
                }

                _disposed = true;
            }
        }

        #endregion

        #region 内部类

        /// <summary>
        /// DNS服务器信息
        /// </summary>
        /// <remarks>
        /// 初始化DNS服务器信息
        /// </remarks>
        /// <param name="name">服务器名称</param>
        /// <param name="primaryDns">主DNS服务器</param>
        /// <param name="secondaryDns">备用DNS服务器</param>
        private class DNSServer(string name, string primaryDns, string secondaryDns = "")
        {
            /// <summary>
            /// 服务器名称
            /// </summary>
            public string Name { get; } = name;

            /// <summary>
            /// 主DNS服务器
            /// </summary>
            public string PrimaryDns { get; } = primaryDns;

            /// <summary>
            /// 备用DNS服务器
            /// </summary>
            public string SecondaryDns { get; } = secondaryDns;
        }

        #endregion
    }
}